<?php
use Qiniu\Storage\UploadManager;
use Qiniu\Auth;

require __DIR__.'/../php-sdk-7.0.8/autoload.php';
$config=require __DIR__.'/config.php';
require __DIR__.'/Log.php';
require __DIR__.'/Delete.php';

$time=date('Y-m-d H:i:s', time());

$temp_config=json_encode($config);
$context="备份网站-{$time}_{$temp_config}开始执行";
Log::write($context);
$t1 = microtime(true);

$accessKey=$config['accessKey'];
$secretKey=$config['secretKey'];

$auth = new Auth($accessKey, $secretKey);


// 要上传的空间
$bucket = $config['bucket'];

// 生成上传 Token
$token = $auth->uploadToken($bucket);

$file_path=__DIR__.'/../temp/web.tar.gz';

echo $file_path;
// 上传到七牛后保存的文件名
$rands=rand(5000,9999);
$key = "${time}_网站备份_{$rands}.tar.gz";

// 初始化 UploadManager 对象并进行文件的上传。
$uploadMgr = new UploadManager();


// 调用 UploadManager 的 putFile 方法进行文件的上传。
list($ret, $err) = $uploadMgr->putFile($token, $key, $file_path);

if ($err !== null) {
    var_dump("上传失败!");
    var_dump($err);
    Log::write("上传失败".json_encode($err));
} else {
    $URL="http://p7h441d6x.bkt.clouddn.com/";
    $URL=$URL . $ret['key'];
    $context="{$time}上传成功!{$ret['key']}";
    Log::write($context);


    $config=Log::get();
    $file_name=$key;
    $arr=[];

    $arr_object=json_decode($config);

    foreach ($arr_object as $key=>$item) {
        $arr[$key]=$item;
    }

    var_dump($arr);
    var_dump(count($arr));


    if(empty($arr)){
        $temp[0]=$file_name;
        Log::run(json_encode($temp));
        die;
    }

    if(count($arr)<3){
        $arr[]=$file_name;
        Log::run(json_encode($arr));
    }

//开始删除文件了
    if(count($arr)>=3){
        Delete::delete($arr[0]);  //开始调用骑牛的删除的方法
        array_splice($arr, 0, 1);
        $arr[]=$file_name;
        Log::run(json_encode($arr));
    }
}

$t2 = microtime(true);
Log::write('耗时'.round($t2-$t1,3).'秒');

Log::write('===========================================================');
